package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

import model.DailyMission;

import db.DbConn;

public class DailyMissionServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	DbConn conn;

	@Override
	public void init() throws ServletException {
		conn = new DbConn();
		conn.setDbUrl(getServletContext().getInitParameter("dbUrl"));
		conn.setDbUser(getServletContext().getInitParameter("dbUser"));
		conn.setDbPass(getServletContext().getInitParameter("dbPass"));
	}

	// Daily mission 실행 시킬때 필요한 dailyData 를 가지고 뿌려주기
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		String userId = (String) session.getAttribute("userId");
		HashMap<String, Object> data = conn.getDailyInitData(userId);
		if (data.containsKey("error")) {
			resp.setCharacterEncoding("UTF-8");
			PrintWriter out = resp.getWriter();
			out.println("<script type='text/javascript'>");
			out.println("alert('" + data.get("오늘은 이미 완료를 하였습니다.") + "');");
			out.println("location.href='logonIndex.jsp';");
			out.println("</script>");
			out.flush();

		} else {
			data.toString();
			req.setAttribute("dailyData", data);
			RequestDispatcher dispatcher = req
					.getRequestDispatcher("dailymission.jsp");
			dispatcher.forward(req, resp);
		}
	}

	// Daily mission 실행을 시키고 난 후 정보를 db 에 저장하는 부분
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 인코딩 세팅
		req.setCharacterEncoding("UTF-8");
		if("on".equals(req.getParameter("sns_check"))) {
			try{
				
			String consumerKey = getServletContext().getInitParameter("ConsumerKey");
			String consumerSecret = getServletContext().getInitParameter("ConsumerSecret");
			StringTokenizer access = new StringTokenizer(conn.getAccessToken((String)req.getSession().getAttribute("userId")), "&");
			String token = (String)access.nextToken();
			String tokensecret = (String)access.nextToken();
			Twitter twt = new TwitterFactory().getInstance();
			AccessToken act = new AccessToken(token, tokensecret);
			twt.setOAuthConsumer(consumerKey, consumerSecret);
			twt.setOAuthAccessToken(act);
			twt.updateStatus(req.getParameter("comment"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		DailyMission dailymission = new DailyMission();
		dailymission
				.setUserId((String) req.getSession().getAttribute("userId"));
		dailymission.setProgramId(req.getParameter("programid"));
		dailymission.setTodayWeight(Integer.parseInt(req
				.getParameter("todayweight")));
		dailymission.setComment(req.getParameter("comment"));
		dailymission.setIsCheckFood1(req.getParameter("foodlist1"));
		dailymission.setIsCheckFood2(req.getParameter("foodlist2"));
		dailymission.setIsCheckFood3(req.getParameter("foodlist3"));
		dailymission.setIsCheckExer1(req.getParameter("exerlist1"));
		dailymission.setIsCheckExer2(req.getParameter("exerlist2"));
		dailymission.setIsCheckExer3(req.getParameter("exerlist3"));
		conn.setCurrentProject(dailymission);

		boolean isfinished = conn.isFinishedProject((String) req.getSession()
				.getAttribute("userId"));
		if (isfinished == true) {
			conn.giveUpCurrentProject((String) req.getSession().getAttribute(
					"userId"));
			resp.setContentType("text/html");
			resp.setCharacterEncoding("UTF-8");
			PrintWriter out = resp.getWriter();
			out.println("<script type='text/javascript'>");
			out.println("alert('프로그램이 모두 완료되어  프로젝트를 종료시킵니다. 수고하셨습니다.');");
			out.println("location.href='logonIndex.jsp';");
			out.println("</script>");
			out.flush();
		} else {
			resp.setContentType("text/html");
			resp.setCharacterEncoding("UTF-8");
			PrintWriter out = resp.getWriter();
			out.println("<script type='text/javascript'>");
			out.println("alert('저장되었습니다.!');");
			out.println("location.href='logonIndex.jsp';");
			out.println("</script>");
			out.flush();
		}
	}
}
